﻿namespace ApiTemplate.WebApi.Controllers.Base
{
    /// <summary>
    /// 基础的api控制器
    /// </summary>
    [Route("api/[controller]/[action]")]
    [ApiController]
    public class BaseApiController : ControllerBase
    {
        /// <summary>
        /// 可以直接使用属性注入
        /// </summary>
        public ICacheHelper CacheHelper { get; set; }

        /// <summary>
        /// 注入映射对象
        /// </summary>
        public IMapper Mapper { get; set; }

        /// <summary>
        /// 获取当前登录用户信息
        /// </summary>
        /// <returns></returns>
        protected async Task<UserLoginOutput> GetCurrentUserInfoAsync()
        {
            string userToken = HttpContext.Request.Headers["UserToken"];
            if (string.IsNullOrEmpty(userToken))
            {
                throw new BusinessException
                {
                    Code = ErrorCode.UnAuthorized,
                    ErrorMessage = "未授权的请求"
                };
            }
            else
            {
                return await CacheHelper.GetEntityAsync<UserLoginOutput>(userToken, 30);
            }
        }

        /// <summary>
        /// 是否登录
        /// </summary>
        /// <returns></returns>
        protected async Task<bool> IsLoginAsync()
        {
            string userToken = HttpContext.Request.Headers["UserToken"];
            if (string.IsNullOrEmpty(userToken))
            {
                return false;
            }
            else
            {
                var user = await CacheHelper.GetEntityAsync<UserLoginOutput>(userToken, 30);
                return user != null;
            }
        }

        /// <summary>
        /// 获取真实IP
        /// </summary>
        /// <returns></returns>
        protected string GetRealIp()
        {
            string ip;
            if (Request.Headers.ContainsKey("X-Forwarded-For"))
            {
                ip = Request.Headers["X-Forwarded-For"];
            }
            else if (Request.Headers.ContainsKey("X-Real-IP"))
            {
                ip = Request.Headers["X-Real-IP"];
            }
            else
            {
                ip = HttpContext.Connection.RemoteIpAddress.MapToIPv4().ToString();
            }
            return ip;
        }
    }
}
